import React, {Component} from "react";
import {DeviceEventEmitter, Image, ListView, ScrollView, Text, TouchableOpacity, View} from "react-native";
import {Button, DatePicker, Flex, InputItem, List, Modal, Picker, Popup, WhiteSpace} from "antd-mobile";
import {createForm} from "rc-form";
import moment from "moment";
import "moment/locale/zh-cn";

import * as Libs from "../../libs/Libs";
import HTTP from "../../libs/HTTP";
import {saveStorageRecord, signedContractList, storageInfoList} from "../../libs/api";
import {RefreshListView, RefreshState, SuccessResult} from "../../widget";
import ScanModal from "../../widget/ScanModal";

import BatchEnterWrapper from '../common/BatchEnterWrapper'
import HandEnterPopUp from '../common/HandEnterPopUp'
import BatchScanCode from '../common/BatchScanCode'
import ScanCodeCell from '../common/ScanCodeCell'

const Item = List.Item
const Brief = Item.Brief
const zhNow = moment().locale('zh-cn').utcOffset(8)

const scancodeImg = require('../../img/Normal/scancode.png')
const handenterImg = require('../../img/Normal/handenter.png')
const cameraImg = require('../../img/Normal/camera.png')
const batchImg = require('../../img/Normal/batch.png')

const alert = Modal.alert

class EntryAddInner extends Component {

  static navigationOptions = ({ navigation }) => ({
    title: '出库添加',
    headerTintColor: 'white',
    headerStyle:{ backgroundColor: '#39C0E7'}
  })

  listView: RefreshListView
  batchListView: RefreshListView

  constructor(props) {
    super(props)
    this.batchDs = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 })
    this.ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 })
    this.innerData = []
    this.batchInnerData = []
    this.listener = undefined
    this.state = {
      producerOrganNo: undefined,
      submitSuccess: false,
      scanVisible: false, //扫码抢是否显示
      createTime: zhNow,
      producerInfo: [],
      storageInfo: [{
        value: '0',
        label: '默认仓库'
      }],
      storageVal: undefined,
      batchScanMaterials: this.batchDs.cloneWithRows(this.batchInnerData),
      scanMaterials: this.ds.cloneWithRows(this.innerData)
    }
  }

  componentWillMount() {
    console.log('entryadd will mount')
    this.listener = DeviceEventEmitter.addListener('SCANCODE', (v) => {
      console.log('entry add scan code invoke ..')
      const value = v.value
      this.addSubMaterials(value)
    })
  }

  componentWillUnmount() {
    console.log('entryadd unmount')
    this.listener.remove()
  }

  componentDidMount() {
    HTTP.post(signedContractList(), {dealerOrganNo: Libs.getOrganNo()}, () => {}, (resp = []) => {
      let producerInfo = this.state.producerInfo
      resp.map((v, i) => {
        producerInfo.push({
          value: v['producerOrganNo'],
          label: v['producerOrganName']
        })
      })
      console.log('producerinfo,', producerInfo)
      this.setState({
        producerInfo: producerInfo
      })
    })
    HTTP.post(storageInfoList(), {dealerOrganNo: Libs.getOrganNo()}, () => {}, (resp) => {
      const storageInfo = resp || []
      let _storInfo = this.state.storageInfo
      storageInfo.map((v, i) => {
        _storInfo.push({
          value: v.id + '',
          label: v.storageName
        })
      })
      this.setState({
        storageInfo: _storInfo
      })
    })
  }

  onTimeChange = (date) => {
    this.setState({
      createTime: date
    })
  }

  onScanSuccess = (value) => {
    this.addSubMaterials(value)
    this.hideScanModal()
  }
  showScanModal = () => {
    this.setState({
      scanVisible: true
    })
  }
  hideScanModal = () => {
    this.setState({
      scanVisible: false
    })
  }
  invokeScan = () => {
    this.showScanModal()
  }

  renderHeader() {
    const { getFieldProps, getFieldError } = this.props.form;
    return (
      <View>
        <List>
          <Picker
            data={this.state.producerInfo}
            cols={1}
            onOk={v => {
              this.setState({
                producerOrganNo: v[0]
              })
            }}
            {...getFieldProps('producerId')}
          >
            <List.Item arrow="horizontal">厂方</List.Item>
          </Picker>
          <DatePicker
            mode="date"
            onChange={this.onTimeChange}
            value={this.state.createTime}
          >
            <List.Item arrow="horizontal">日期</List.Item>
          </DatePicker>
          <InputItem
            {...getFieldProps('linkCustomer')}
          >客户</InputItem>
          <Picker
            value={this.state.storageVal}
            onChange={v => {
              console.log('selected', v)
              this.setState({ storageVal: v })
            }}
            data={this.state.storageInfo}
            cols={1}
            {...getFieldProps('storageId', {
              initialValue:['0']
            })}
          >
            <List.Item arrow="horizontal">仓库</List.Item>
          </Picker>
          <InputItem
            {...getFieldProps('linkOrderNo')}
          >单号</InputItem>
        </List>
        <WhiteSpace />
        <Flex style={{backgroundColor: 'white', paddingVertical: 5}}>
          <Flex.Item>
            <TouchableOpacity onPress={() => {console.log('scancode')}}>
              <View style={{alignItems: 'center'}}>
                <Image source={scancodeImg} style={{width: 30, height: 28}}/>
                <Text>扫码枪</Text>
              </View>
            </TouchableOpacity>
          </Flex.Item>
          <Flex.Item>
            <TouchableOpacity onPress={this.invokeScan}>
              <View style={{alignItems: 'center'}}>
                <Image source={cameraImg} style={{width: 28, height: 28}} />
                <Text>相机</Text>
              </View>
            </TouchableOpacity>
          </Flex.Item>
          <Flex.Item>
            <TouchableOpacity onPress={this.invokeHandEnter} >
              <View style={{alignItems: 'center'}}>
                <Image source={handenterImg} style={{width: 28, height: 28}}/>
                <Text>手工输入</Text>
              </View>
            </TouchableOpacity>
          </Flex.Item>
          <Flex.Item>
            <TouchableOpacity onPress={this.invokeBatchEnter} >
              <View style={{alignItems: 'center'}}>
                <Image source={batchImg} style={{width: 28, height: 28}}/>
                <Text>批量添加</Text>
              </View>
            </TouchableOpacity>
          </Flex.Item>
        </Flex>
        <WhiteSpace />
        {
          <ScanModal visible={this.state.scanVisible} hide={this.hideScanModal} onSuccess={this.onScanSuccess}/>
        }
      </View>
    )
  }

  onEnter = () => {
    this.props.navigation.navigate('OutInnerBoundStack')
  }

  render() {
    const { getFieldProps, getFieldError } = this.props.form
    if(this.state.submitSuccess) {
      return (
        <SuccessResult onEnter={this.onEnter}/>
      )
    } else {
      return (
        <View style={{flex: 1}}>
          <ScrollView>
            {
              this.renderHeader()
            }
            <RefreshListView
              ref={(e) => this.batchListView = e}
              defaultState={RefreshState.Idle}
              dataSource={this.state.batchScanMaterials}
              renderHeader={() => {
              }}
              renderRow={(rowData) => {
                return (
                  <BatchScanCode key={rowData} code={rowData} delFunc={this.delBatchFuncInvoke}></BatchScanCode>
                )
              }}
            />
            <RefreshListView
              ref={(e) => this.listView = e}
              defaultState={RefreshState.Idle}
              dataSource={this.state.scanMaterials}
              renderHeader={() => {
              }}
              renderRow={(rowData) => {
                return (
                  <ScanCodeCell producerOrganNo={this.state.producerOrganNo} key={rowData} code={rowData} delFunc={this.delFuncInvoke}></ScanCodeCell>
                )
              }}
            />
          </ScrollView>
          <View>
            <View><Text>件数合计: {this.caclCount()}</Text></View>
            <Button onClick={this.onSubmit} inline>提交</Button>
          </View>
        </View>
      )
    }
  }

  caclCount = () => {
    let count = this.innerData.length
    this.batchInnerData.map((v, i) => {
      console.log('v', v)
      count += parseInt(v.substring(v.indexOf('@') + 1))
    })
    return count
  }

  delBatchFuncInvoke = (code) => {
    console.log('del code: ', code)
    let idx = this.batchInnerData.indexOf(code)
    if(idx !== -1) {
      this.batchInnerData.splice(idx, 1)
      let newD = this.batchInnerData.slice(0)
      console.log('new Data: ', newD)
      this.setState({
        batchScanMaterials: this.batchDs.cloneWithRows(newD.reverse())
      })
    }
  }

  delFuncInvoke = (code) => {
    console.log('del code: ', code)
    let idx = this.innerData.indexOf(code)
    if(idx !== -1) {
      this.innerData.splice(idx, 1)
      let newD = this.innerData.slice(0)
      console.log('new Data: ', newD)
      this.setState({
        scanMaterials: this.ds.cloneWithRows(newD.reverse())
      })
    }
  }

  onMaskClose = () => {
    console.log('on Mask close')
  }

  invokeHandEnter = (e) => {
    e.preventDefault()
    Popup.show(<HandEnterPopUp
      onSave={this.addSubMaterials}
      onClose={() => {Popup.hide()}}
    />, {
      onMaskClose: this.onMaskClose,
      maskClosable: false
    })
  }

  invokeBatchEnter = (e) => {
    e.preventDefault()
    Popup.show(<BatchEnterWrapper
      onSave={this.addBatchMaterials}
      onClose={() => { Popup.hide() }}
    />, {
      maskClosable:false
    })
  }

  addBatchMaterials = (value) => {
    this.batchInnerData.push(value)
    const newD = this.batchInnerData.slice(0)
    this.setState({
      batchScanMaterials: this.batchDs.cloneWithRows(newD.reverse())
    })
  }

  addSubMaterials = (num) => {
    if(this.innerData.indexOf(num) !== -1) {
      alert('提示', '编号已录入')
      return false
    }
    this.innerData.push(num)
    const newD = this.innerData.slice(0)
    this.setState({
      scanMaterials: this.ds.cloneWithRows(newD.reverse())
    })
  }

  onSubmit = () => {
    this.props.form.validateFields({ force: true }, (error) => {
      if (!error) {
        if(this.innerData.length == 0 && this.batchInnerData.length == 0) {
          alert('提示', '没有相应物品，请扫码或手工输入')
          return false
        }
        const values = this.props.form.getFieldsValue();
        const id = Libs.getCurrentUser().id
        const organNo = Libs.getCurrentUser().organNo

        values.linkCustomer = values.linkCustomer //关联客户
        values.linkOrderNo = values.linkOrderNo //关联单号
        values.storageId = values.storageId.join(',')  //仓库
        values.producerOrganNo = values.producerId.join(',')
        values.actionTime = this.state.createTime.toDate() //入库/出库时间
        values.erCodes = this.innerData.join(",") //记录内容,号分割
        values.batchErCodes = this.batchInnerData.join(",")
        values.recordType = '2' //记录类型
        values.operatorId = id //操作人
        values.dealerOrganNo = organNo

        HTTP.post(saveStorageRecord(), values, () => {}, (resp) => {
          this.setState({
            submitSuccess: true
          })
        }, () => {
          alert('提示', '保存失败')
        })
      } else {
        console.log(error)
        alert('提示', '验证失败');
      }
    });
  }
}

export default createForm()(EntryAddInner)
